package dataint;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.xml.sax.InputSource;



/**
 * Class to connect to the XML-File, parse the data, cleanse it and generate a customer list.
 */
public class XMLSource extends DataSource {

    // represents the XML file
    private Document doc;

    // contains the XML root element
    private Element root;

    // is the namespace of the XML file
    private Namespace xmlns = Namespace.getNamespace("http://dbis-group.uni-muenster.de");
    
    /**
     * XMLSource constructor calling internal methods
     */
    public XMLSource() {
	this.parse();
	this.cleanse();
    }

    /**
     * reads the XML file and finds the root element
     */
    public void parse() {

        try {
            SAXBuilder sxbuild = new SAXBuilder();
            //InputSource is = new InputSource("source3.xml");
            InputSource is = new InputSource("http://penelope.uni-muenster.de/dataint/source3.xml");
            doc = sxbuild.build(is);
            root = doc.getRootElement();
        }
        catch (JDOMException j) {
            System.out.println( "JDOMException in XMLSource.parse(): " + j.toString());
            System.exit(0);
        }
        catch (IOException e) {
            System.out.println("IOException in XMLSource.parse(): " + e.toString());
        }
    }

    /**
     * reads the XML file takes the data and creates a new customer object
     */
    public void cleanse(){

        try {
            List<Element> orderList = root.getChildren();
            for (Element order: orderList) {
                Element customerInfo = order.getChild("CustInfo",xmlns);
                Customer newCustomer = new Customer();
                newCustomer.setFirstName(this.makeFirstName(customerInfo.getChildText("Name", xmlns)));
                newCustomer.setLastName(this.makeLastName(customerInfo.getChildText("Name", xmlns)));
                newCustomer.setCity(customerInfo.getChildText("City", xmlns));
                newCustomer.setEmail(customerInfo.getChildText("Email", xmlns));
                newCustomer.setPhoneNo(this.makePhoneNumer(customerInfo.getChildText("Phone", xmlns)));
                newCustomer.setStreetAddress(customerInfo.getChildText("Address", xmlns));
                newCustomer.setPremium("");
                newCustomer.setDate("");
                newCustomer.setTOV(new Double(order.getChild("OrderInfo",xmlns).getChildText("GrandTotal", xmlns)));
                putInList(newCustomer);
            }
        }
        catch (Exception j) {
            System.out.println("Exception in XMLSource.cleanse(): "+j.toString());
            System.exit(0);
        }
    }

    /**
     * takes a customer and puts it in the customerList. If the customer
     * is already in the list the total order values gets added the the
     * customer already in the list.
     *
     * @param cust Customer object to be put in the customer list
     */
    private void putInList(Customer cust){
        for(Customer customer: this.customerList) {
            if (customer.equals(cust)) {
                customer.setTOV(customer.getTOV() + cust.getTOV());
                return;
            }
        }
        this.customerList.add(cust);
        return;
    }

    /**
     * Converts a String (full name) to a first name (including middle name)
     *
     * @param fullString
     * @return first name (includes middle name)
     */
    private String makeFirstName(String fullString){
        int i;
        String firstName = "";
        String[] tokens = fullString.split(" ");
        for (i = 0; i < (tokens.length - 1); i++) // omit the last string token
        {
            firstName = firstName + tokens[i] + " ";
        }
        return firstName.trim();
    }

    /**
     * Converts a String (full name) to a last name
     * @param fullString
     * @return last name
     */
    private String makeLastName(String fullString) {
        String[] tokens = fullString.split(" ");

        return tokens[tokens.length - 1];
    }

    /**
     * Converts a String (phone number) to the correct phone number pattern
     *
     * @param fullString
     * @return phone number string
     */
    private String makePhoneNumer(String fullString) {
        //return fullString;
        String number = fullString;

        number = number.replace(" ", "");
        number = number.replace("/", " ");
        number = number.replace("(", "");
        number = number.replace(")", "");
        if (number.startsWith("+49")) {
            number = number.substring(3);
        }
	else if (number.startsWith("49")) {
            number = number.substring(4);
        }
	else if (number.startsWith("0049")) {
            number = number.substring(4);
        }
	if (!number.startsWith("0")) {
            number = "0".concat(number);
        }
        return number;
    }
}
